package com.tencent.qf.common.gateway.scrm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author: p_haojiawu@tencent.com
 * @date: 2023-01-06 11:34
 **/
@Slf4j
@Component
public class SCRMClient {
    @Resource
    private RestTemplate httpClientTemplate;
    @Resource
    private SCRMProperties scrmProperties;

    public String post(SCRMCommonRequest request, String apiPath) {
        long timestamp = new Date().getTime() / 1000;
        request.setTime(timestamp);
        request.setAppkey(scrmProperties.getAppid());
        String sign = SCRMApiUtils.sign(scrmProperties.getAppid(), scrmProperties.getSecretKey(), timestamp);
        if (StringUtils.hasText(sign)){
            request.setSign(sign);
        }
        HttpHeaders headers = new HttpHeaders();
        SerializeConfig config = new SerializeConfig();
        // 把驼峰转为下划线
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        headers.add("Content-Type", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(request,config), headers);
        try{
            log.info("post请求SCRM{} 入参{}", apiPath,JSON.toJSONString(request,config));
            ResponseEntity<String> responseEntity = httpClientTemplate.postForEntity(scrmProperties.getUrl()
                    + apiPath, entity, String.class);
            log.info("post请求SCRM{} 出参{}", apiPath, JSON.toJSONString(responseEntity));
            if(responseEntity.getStatusCode() == HttpStatus.OK){
                return responseEntity.getBody();
            }
        }catch (Exception e){
            log.error("post请求SCRM{}, error{}", apiPath, e);
            return e.getMessage();
        }
        return null;
    }
}
